import React, { Component } from 'react';
import { Tabs, List, Button, Table, Divider, Modal, Form, Input, Icon, Popover, InputNumber, Switch, notification, Select, Cascader, Drawer, Row, Col, Popconfirm } from 'antd';
import '@/assets/css/settings';
import * as APIService from '../../axios/api';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
//弹出通知提醒框
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};

class App extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [],
		visible: false, //显示与隐藏
		modalData: '',//选中的数据
		handleType: 0,//新增0 修改1
		topId: 0,
	};
	componentDidMount() {
		this.fetch();
	}
	//初始化加载数据
	fetch = () => {
		this.setState({ loading: true })
		APIService.getDepartMents().then(data => { //发送axios请求---部门查询
			const dataSource = data.data.data;
			this.setState({
				dataSource: dataSource,
				loading: false,
			})
		})
	}
	handleChangeTab = key => {
	};

	//添加修改部门提交
	submitMenu = (e) => {
		this.props.form.validateFields((err, values) => {
			if (!err) {

				if (this.state.handleType === 0) {
					values = Object.assign({}, values, { creatorId: parseInt(localStorage.getItem('userId')), parentId: this.state.modalData.id === undefined ? null : this.state.modalData.id })
				} else {
					values = Object.assign({}, values, { updaterId: parseInt(localStorage.getItem('userId')), parentId: this.state.modalData.parentId, id: this.state.modalData.id })
				}
				const that = this;
				APIService.addDepartMent(values).then(data => {
					if (data.data.code === 200) {
						openNotification('success', '操作成功')
					} else {
						openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.props.form.resetFields();
					that.fetch();
				})

			} else {
				console.log(err);
			}
		});
	}


	//弹出删除框
	showDeleteConfirm = (data) => {
		const that = this;
		confirm({
			title: '确认删除' + '[' + data.name + ']？',
			okText: '确认',
			okType: 'danger',
			cancelText: '取消',
			onOk() {
				if (data.children.length === 0) {
					APIService.deleteDepartMent(data.id).then(data => {
						openNotification('success', '删除成功');
						that.fetch();
					}).catch(function (error) {
						openNotification('error', error.message);
					});
				} else {
					openNotification('warning', '权限有子权限');
				}



			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}

	onExpand = (expanded, record) => {
		// console.log('这是', expanded, record);
	}

	//0新增  1修改
	showModal = (data, type) => {
		const that = this;
		if (type === 1) {
			this.props.form.setFieldsValue({
				name: data.name,
				code: data.code,
				description: data.description
			})
		}

		this.setState({
			visible: true,
			modalData: data,
			handleType: type,
		});

	};



	handleCancel = e => {
		this.props.form.resetFields();//清除form表单控件的值
		this.setState({
			visible: false,
		});
	};

	render() {
		const columns = [
			{
				dataIndex: '',
				width: '80px'
			},
			{
				title: '部门编码',
				dataIndex: 'code',
			},
			{
				title: '序号',
				width: '10%',
				render: (text, record, index) => `${index + 1}`,
			},
			{
				title: '部门名称',
				dataIndex: 'name',
			},
			{
				title: '描述',
				dataIndex: 'description',
			},
			{
				title: '操作',
				width: '12%',
				render: (text, record, index) => {
					return <span>
						{
							record.number !== null && <a onClick={() => this.showModal(record, 0)}>添加</a>
						}
						{
							record.number !== null && <Divider type="vertical" />
						}
						<a onClick={() => this.showModal(record, 1)}>修改</a>
						<Divider type="vertical" />
						<a onClick={() => this.showDeleteConfirm(record)}>
							删除
						</a>
					</span>
				}
			}
		];


		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
			labelCol: {
				xs: {
					span: 30
				},
				sm: {
					span: 10
				},
			},
			wrapperCol: {
				xs: {
					span: 24
				},
				sm: {
					span: 14
				},
			},
		};
		//设置表单的排布--类栅格
		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
		};
		// 新增按钮
		var operations = <div className="mydiv" > <Button icon="plus" onClick={() => this.showModal([], 0)} type="primary" > 新增 </Button></div >
		return (
			<div className="shadow-radius">
				{/* //      额外的元素     ↓ 新增按钮  */}
				<Tabs tabBarExtraContent={operations} defaultActiveKey="1" onChange={this.handleChangeTab}>
					<TabPane tab="部门管理" key="1">
						{/*     列的配置          表格行 key 的取值              数据     */}
						<Table columns={columns}
							rowKey={(record) => record.id}
							dataSource={this.state.dataSource}
							pagination={false}
							loading={this.state.loading}
							onExpand={(expanded, record) => this.onExpand(expanded, record)} />
						{/*                    点击展开图标时触发 */}
					</TabPane>

				</Tabs>

				<Modal
					width='600px'
					title="新增/修改"
					visible={this.state.visible}
					centered
					onOk={this.submitMenu}
					onCancel={this.handleCancel}
					okText="保存"
					cancelText="取消"
				>
					<Form {...formItemLayout_addMenu}>
						<Form.Item label="部门编码">
							{getFieldDecorator('code', {
								rules: [{ required: true, message: '请填写部门编码！' }]
							})(<Input />)}
						</Form.Item>
						<Form.Item label="部门名称">
							{getFieldDecorator('name', {
								rules: [{ required: true, message: '请填写部门名称！' }]
							})(<Input />)}
						</Form.Item>
						<Form.Item label="描述">
							{getFieldDecorator('description')(<textarea style={{ width: '100%', height: '4rem' }} />)}
						</Form.Item>

					</Form>

				</Modal>



			</div>
		);
	}
}
export default Form.create()(App);